<template>
	<view class="manage-item">
		<view class="top">
			<view class="top-header">
				<text v-if="item.is_recommend==1">[首页推荐]</text> 
				<text class="name">{{ item.title }}</text>
			</view>
			<text class="green">{{status}}</text>
			<!-- <uni-icons type="scan" size="20"></uni-icons> -->
		</view>
		<view class="container">
			<view class="row">
				<!-- 状态0=使用中1=已停止2=已关闭3=首页推荐4=置顶 -->
				<text class="label">分类：</text>
				<text class="black">【{{type}}】</text>
			</view>
			<view class="row">
				<text class="label">排序号：</text><text>{{item.order_num}}(小的先显示)</text>
			</view>
			<!-- <view class="row">
				<text class="label">排期：</text><text>{{ item.days }}天可预约</text>
			</view> -->
			<view class="row">
				<text class="label">创建：</text><text>{{ item.create_time}}</text>
			</view>
			<view class="btns">
				<view class="btn" @click="edit(item)">
					<text class="iconfont icon-shezhi"></text>
					<text>编辑</text>
				</view>
				<view class="btn" @click="manageState(item.id)">
					
					<text>状态管理</text>
				</view>
				<view class="btn" @click="moreSetting(item.id,ctype)">
					<text class="iconfont icon-zidonghexiao"></text>
					<text>更多操作</text>
				</view>
				<view class="btn" @click="preview(item.id)">
					<text>预览</text>
				</view>
			</view>
		</view>
		<!-- 弹框 -->
		<PopupCom ref="popupcom" @confirm-popup="confirmPopup" @update="update" :state="state">
			<view class="uni-list">
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-db">正常</view>
					<switch :disabled="itemObj.status==0?true:false" :checked="itemObj.status==0?stateT:stateF" @change="myChoose0(0)" />
				</view>
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-db">停用</view>
					<switch :disabled="itemObj.status==1?true:false" :checked="itemObj.status==1?stateT:stateF" @change="myChoose1(1)" />
				</view>
				<view class="uni-list-cell uni-list-cell-pd">
					<view class="uni-list-cell-db">最新</view>
					<switch :disabled="itemObj.status==2?true:false" :checked="itemObj.status==2?stateT:stateF" @change="myChoose2(2)" />
				</view>
				
			</view>
		</PopupCom>
		
		<!-- <image :src="bufferImg" style="width: 200px;height: 200px"></image> -->
	</view>
</template>

<script>
	import * as XLSX from '../../utils/excel.js'
	import { GetLi, EditNewsState, DelNews, UptoTops,ToRecommends } from '../../api/index.js'

	export default {
		name:"NewsItem",
		props:{
			item:{
				type:Object,
				default:()=>{}
			},
			ctype:{
				type:String,
				default:'1'
			}
		},
		data() {
			return {
				itemObj:this.item,
				stateF:0,
				stateT:1,
				state:0,
				bufferImg:''
			};
		},
		computed:{
			status(){
				let is =this.item.status
				// 状态0=使用中1=已停止2=已关闭3=首页推荐4=置顶
				// if(is==0){
				// 	return '使用中'
				// }
				// return this.item.status
				let res
				switch(is){
					case 0:
						res='正常';
						break;
					case 1:
						res='停用';
						break;
					case 2:
						res='最新';
						break;
				}
				console.log(res,'res')
				return res
			},
			type(){
				let is =this.item.status
				// 状态0=使用中1=已停止2=已关闭3=首页推荐4=置顶
				// if(is==0){
				// 	return '使用中'
				// }
				// return this.item.status
				let res
				switch(is){
					case 0:
						res='服务介绍';
						break;
					case 1:
						res='最新动态';
						break;
					case 2:
						res='优惠活动';
						break;
				}
				console.log(res,'res')
				return res
			},
			// 修改props: {
				itemProps:{
					get() {
						return this.item
					},
					set(value) {
						this.$emit('update:item',value)
						console.log(value)
					}
				}
		},
		watch:{
			'item.status'(value){
				console.log(value,'vvvv')
				this.itemObj.status = value
				this.$emit('updateItem',this.itemObj)
			}
			
		},
		methods:{
			// checkTables(){
			// 	const fileName='打卡'
			// 	    const header = ['date', 'defaultType', 'device']
			// 	    const headerName = { date: '相识日期', defaultType: '类型', device: '姓名' }
			// 	    const ExcelData = [{ date: '2022-02-02', defaultType: '御姐', device: '学姐' }, { date: '2022-02-03', defaultType: '萝莉', device: '学妹' }]
			// 	    XLSX.excel_exprot(ExcelData, header, headerName,fileName)
			
			// },
			edit(item){
				console.log(item,'item')
				uni.navigateTo({
					url:'/subPackageAdmin/NewsForm/NewsForm?item='+JSON.stringify(item)
				})
			},
			manageState(id){
				this.$refs.popupcom.open()
				this.id = id
				console.log(id,'id',this.id)
			},
			async confirmPopup(){
				const dataParam = {
					id:this.id,
					state:this.state
				}
				const {data:res} = await EditNewsState(dataParam)
				if(res.status==0){
					this.item.status = this.state
					
				}
				console.log(res,'resdata')
			},
			update(e){
				console.log(e,this.state)
				this.item.status =e
			},
			myChoose0(e){
				console.log(e)
				this.state = e
				if(e){
					this.state=0
				}
			},
			myChoose1(e){
				console.log(e)
				this.state=0
				this.state = e
				
			},
			myChoose2(e){
				console.log(e)
				this.state=0
				this.state = e
				
			},
			// 删除
			async delNews(id){
				const { data:res } = await DelNews(id)
				console.log(res,'del')
				let that = this
				if(res.status==0){
					this.$emit('updateHelper',{id:that.id,type:'del'})
					uni.showToast({
						title:res.message,
						icon:'success',
						success() {
							console.log('SSS',that)
							
						}
					})
				}
			},
			// 更多
			moreSetting(id,ctype){
				console.log(id,ctype,'ctype')
				this.id = id
				let that = this
				// 动态
				// let items = ['置顶','删除','取消首页推荐','生成专属二维码']
				let items = ['置顶','删除','取消首页推荐']
				
				if(ctype=='1'){
					items = items
				}else
				if(ctype=='2'){
					// items[0]='取消推荐'
				}else
				if(ctype=='3'){
					items[0]='取消置顶'
					items[2]='首页推荐'
				}
				uni.showActionSheet({
					itemList:items,
					success(e) {
						console.log(e,'e',items)
						if(e.tapIndex==0&&items[e.tapIndex]=='取消推荐'){
							console.log('取消推荐')
							return that.toRecommend(that.id,0)
						}
						if(e.tapIndex==0&&items[e.tapIndex]=='首页推荐'){
							console.log('推荐')
							return that.toRecommend(that.id,1)
						}
						if(e.tapIndex==1&&items[e.tapIndex]=='取消置顶'){
							console.log('取消置顶')
							return that.upToTop(that.id,0)
						}
						if(e.tapIndex==1&&items[e.tapIndex]=='置顶'){
							console.log('置顶')
							return that.upToTop(that.id,1)
						}
						if(ctype==1&&items[e.tapIndex]=='删除'){
							console.log('删除')
							return that.delNews(that.id)
						}
						// if(e.tapIndex==2){
						// 	return that.delHelper(that.id)
						// }
						if(e.tapIndex==3){
							// return that.shareToggle()
							that.getAccessToken()
							that.getQrCode()
						}
					}
					
				})
			},
			
			moreSettings(){
				uni.showActionSheet({
					itemList:['置顶','删除','取消首页推荐','生成专属二维码'],
					success: (res) => {
					          console.log('选择了第' + (res.tapIndex + 1) + '个选项');
							  if(res.tapIndex==0){
								  // GetLi().then(res=>{
									 //  console.log(res.data,'ff')
								  // })
								  // uni.$http({
									 //  url:'/api/helper/table',
									 //  method:'GET',
									 //  responseType: 'arraybuffer',
								  // }).then(res=>{
									 //  console.log(res,'g')
								  // })
								  uni.$http.get('/api/helper/table').then(res=>{
									  let resData = res.data
									  	console.log(res,'res',resData)
									  										
									  const fileManagerObj = uni.getFileSystemManager() // 获取全局的文件管理器
									             console.log(fileManagerObj,'o');
									             // 文件存储到本地的路径
									             const filePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.xlsx` 
									             fileManagerObj.writeFile({
									                 data: resData, // 拿到的arraybuffer数据
									                 filePath: filePath,
									                 encoding: 'binary',
									                 success: (res) => {
									                     console.log(res) // 成功了的话这里会打印 writeFile:ok
									                     this.viewDoc(filePath)
									                 }
									             })
									  // console.log(res,'hh')
								  })
								  uni.request({
								    url: 'http://192.168.120.43:3002/api/helper/table', // 替换为你的Node.js服务器地址
								    method: 'GET',
									sslVerify:false,
								    responseType: 'arraybuffer', // 设置响应类型为arraybuffer以接收二进制文件
								    success: (res) => {
										let resData = res.data
										console.log(res,'res',resData)
										
								      const fileManagerObj = uni.getFileSystemManager() // 获取全局的文件管理器
								                 console.log(fileManagerObj,'o');
								                 // 文件存储到本地的路径
								                 const filePath = `${wx.env.USER_DATA_PATH}/${new Date().getTime()}.xlsx` 
								                 fileManagerObj.writeFile({
								                     data: resData, // 拿到的arraybuffer数据
								                     filePath: filePath,
								                     encoding: 'binary',
								                     success: (res) => {
								                         console.log(res) // 成功了的话这里会打印 writeFile:ok
								                         this.viewDoc(filePath)
								                     }
								                 })
		
									  
									
								    },
								    fail: (error) => {
								      console.error('导出失败', error);
								    }
								  });
							  }
					        },
					        fail: (err) => {
					          console.log('弹窗取消');
					        }
					
				})
				
			},
			preview(id){
				uni.navigateTo({
					url:'/subPackageAdmin/NewsDetail/NewsDetail?id='+id
				})
			},
			// 打开文件
			viewDoc(filePath) {
			    uni.openDocument({
			        // 直接打开
			        filePath: filePath, // 这里填上面写入本地的文件路径
			        fileType: 'xlsx',
			        showMenu: true, // 右上角是否有可以转发分享的功能，配不配随意
			        success: (res) => {
			            console.log('打开文档成功')
			        }
			    })
			},
			// 置顶
			async upToTop(id,tp){
				let paramsData = {
					is_up:tp
				}
				const { data:res } = await UptoTops(id,paramsData)
				console.log(res,'置顶')
				// this.$emit('updateHelper',{id:this.id,type:'top'})
				if(res.status==0&&tp==1){
					this.$emit('updateHelper',{id:this.id,type:'top'})
					uni.showToast({
						title:res.message,
						icon:'success'
					})
				}else{
					this.$emit('updateHelper',{id:this.id,type:'top'})
					uni.showToast({
						title:res.message,
						icon:'success'
					})
				}
			},
			// 首页推荐
			async toRecommend(id,tp){
				let paramsData = {
					is_recommend:tp
				}
				const { data:res } = await ToRecommends(id,paramsData)
				console.log(res,'首页推荐')
				// this.$emit('updateHelper',{id:this.id,type:'rec'})
				if(res.status==0&&tp==1){
					this.$emit('updateHelper',{id:this.id,type:'rec'})
					uni.showToast({
						title:res.message,
						icon:'success'
					})
				}else{
					this.$emit('updateHelper',{id:this.id,type:'rec'})
					uni.showToast({
						title:res.message,
						icon:'success'
					})
				}
			},
			// 获取 access_token
			getAccessToken(){
				let appid = 'wx2145cea62c9ca907'
				let secret = '6da88488232f8138ad2c4493795fdc41'
				uni.request({
					method: "GET",
					url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`,
					success:(result) =>{
						console.log(result,'rreess')
						let access_token = result.data.access_token
						// 获取到 access_token 后 获取二维码
						this.getQrCode(access_token)
					}
				})
			},
			// 获取二维码
			getQrCode(token){
				// 注意 access_token 参数是必须放在url后面 其余参数 要在data里面
				let path = 'pages/index/index'
				uni.request({
					method: "POST",
					responseType: 'arraybuffer', // 注意一定要加 不然返回的Buffer流会乱码 导致无法转base64
					url: `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${token}`,
					data: {
						page: path, // 需要打开的页面路径
						scene: 1 // 这个是需要传递的参数
					},
					success:(result) =>{
						// 拿到buffer流 通过wx.arrayBufferToBase64 转成base64 在页面展示
						// 如果不加请求时 responseType: 'arraybuffer' 则会转码失败
						this.bufferImg = "data:image/png;base64," + wx.arrayBufferToBase64(result.data);
					},
				})
			}
			
			
			
			

		
		
		}
	}
</script>

<style lang="scss">
.uni-list{
	display: flex;
	justify-content: space-evenly;
	padding-top: 100rpx;
}
.popup-content{
	width: 600rpx;
	height: 400rpx;
	border-radius: 15rpx;
	margin: auto auto;
	padding: 30rpx;
	.brns-row{
		display: flex;
		.close{
			flex: 1;
		}
		.confirm{
			flex: 1;
		}
	}
}
.manage-item{
	width: 100%;
	margin-bottom: 30rpx;
	border: 1px solid #eee;
	border-radius: 10rpx;
	
	.top{
		// width: 100%;
		// height: 80rpx;
		// line-height: 80rpx;
		// background: #eee;
		// display: flex;
		// align-items: center;
		// padding: 0 10rpx;
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background: #eee;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 10rpx;
		box-sizing: border-box;
		// border: 1px solid #000;
		.top-header{
			.name{
				font-weight: bold;
				margin-left: 10rpx;
			}
		}
	}
	.container{
		background: #fff;
		padding-bottom: 30rpx;
		.row{
			margin-left: 50rpx;
			line-height: 60rpx;
			height: 60rpx;
			.label{
				font-weight: bold;
			}
		}
		.btns{
			display: flex;
			justify-content: space-around;
			margin-top: 20rpx;
			.btn{
				height: 70rpx;
				line-height: 70rpx;
				background: #e1e1e1;
				padding: 0rpx 20rpx;
				border-radius: 10rpx;
				.iconfont{
					margin-right: 6rpx;
				}
				.icon-zidonghexiao{
					color: orange!important;
				}
			}
		}
	}
}
</style>